<?php

namespace App\Services;

class Service
{
    use ServiceTrait;

    /**
     * 获取分页页码
     *
     * @param \Illuminate\Http\Request $request
     * @return int
     */
    protected function getPage($request)
    {
        return (int)$request->input('page', 1) ?: 1;
    }

    /**
     * 获取分页每页条数
     *
     * @param \Illuminate\Http\Request $request
     * @return int
     */
    protected function getPageSize($request)
    {
        return (int)$request->input('page_size', 10) ?: 10;
    }

    /**
     * 获取数组参数
     *
     * @param \Illuminate\Http\Request $request
     * @param string $key
     * @return array
     */
    protected function getParamArray($request, $key)
    {
        $value = $request->input($key);

        $values = is_array($value) ? $value : json_decode($value, true);

        return is_array($values) ? $values : [];
    }

    /**
     * 获取参数
     *
     * @param \Illuminate\Http\Request $request
     * @param string $key
     * @return array|mixed
     */
    protected function getParam($request, $key)
    {
        $value = $request->input($key);
        if($key == 'currency'){
            $currencys = $request->input('currency', []);
            $currencystr = json_encode($currencys);
            $currencystr = str_ireplace(['"COIN'], '"CNY', $currencystr);
            $value = json_decode($currencystr, true);
        }

        $values = is_array($value) ? $value : json_decode($value, true);

        return is_array($values) ? $values : $value;
    }

    /**
     * 判断参数是否有效
     *
     * @param \Illuminate\Http\Request $request
     * @param string $key
     * @return boolean
     */
    protected function isValidParam($request, $key)
    {
        $value = $this->getParam($request, $key);
        // null
        if(is_null($value)){
            return false;
        }
        // 空字符串
        if(! is_bool($value) && ! is_array($value) && trim((string) $value) === ''){
            return false;
        }
        // 空数组
        if (is_array($value) && count($value) <= 0) {
            return false;
        }
        return true;
    }
}
